package com.SoapClasses;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.util.Log;
import com.Data.Albums;
import com.Data.GeoTag;
import com.Data.PictureInfo;
import com.Data.Post;
import com.Data.User;
import com.Managers.LogManagerClass;


public class SoapPost {

    public static final int UPLOAD_COVER = 400;

    public static final int UPLOAD_PICTURE = 200;

    public static final int UPLOAD_PROFILE = 300;

    private static String TAG = "SOAPPOST";

    private String METHOD_NAME;

    private String SOAP_ACTION;

    SoapSerializationEnvelope envelope;

    PropertyInfo pi;

    SoapObject Request;

    public String deletePicture(int IDOwner, int IDPicture) {

        String METHOD_NAME = "deletePicture";
        String SOAP_ACTION = "http://ShareUp.com/deletePicture";
        //
        Request = new SoapObject(SoapUtil.NAMESPACE, METHOD_NAME);
        //
        String info = IDOwner + "@" + IDPicture + "@";
        Request.addProperty("data", info);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(Request);
        HttpTransportSE httpTransport = new HttpTransportSE(SoapUtil.URL, SoapUtil.TIMEOUT);
        //
        Object response = null;
        try {
            httpTransport.call(SOAP_ACTION, envelope);
            response = envelope.getResponse();
        }
        catch (Exception x) {
            response = x.toString();
            Log.e(TAG + ": ", x.getMessage());
            LogManagerClass.writeLog(TAG + ": " + x.getMessage());
        }

        return response.toString();
    }

    public Post[] getAlbumPictures(int fromPosition, int userID, int myID, Context context) {

        String request = SoapUtil.MODE_ALBUM + "@" + fromPosition
                    + "@" + userID + "@" + myID + "@"
                    + SoapUtil.ALBUM_ID;
        //
        return downloadPicturesInfo(request);
    }

    public Post[] getExplorePictures(int fromPosition, int userID, int myID, Context context) {

        String request = SoapUtil.MODE_EXPLORE + "@" + fromPosition
                    + "@" + userID + "@" + myID + "@"
                    + SoapUtil.ALBUM_ID;
        //
        return downloadPicturesInfo(request);
    }

    public Post[] getFavsPictures(int fromPosition, int userID, int myID, Context context) {

        String request = SoapUtil.MODE_FAVS + "@" + fromPosition
                    + "@" + userID + "@" + myID + "@"
                    + SoapUtil.ALBUM_ID;
        //
        return downloadPicturesInfo(request);
    }

    public Post[] getFriendPictures(int userID, int myID, Context context) {

        String request = SoapUtil.MODE_FOLLOWERS + "@" + 0 + "@"
                    + userID + "@" + myID + "@" + SoapUtil.ALBUM_ID;
        //
        return downloadPicturesInfo(request);
    }

    public Post[] getPublicationInfo(int ID) {

        String request = SoapUtil.MODE_GET_PUBLICATION_INFO + "@"
                    + ID + "@" + 0 + "@" + 0 + "@" + 0;

        return downloadPicturesInfo(request);
    }

    public String getLikedPicture() {

        String METHOD_NAME = "getLikedPicture";
        String SOAP_ACTION = "http://ShareUp.com/getLikedPicture";

        Request = new SoapObject(SoapUtil.NAMESPACE, METHOD_NAME);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(Request);
        HttpTransportSE httpTransport = new HttpTransportSE(SoapUtil.URL, SoapUtil.TIMEOUT);
        //
        Object response = null;
        try {
            httpTransport.call(SOAP_ACTION, envelope);
            response = envelope.getResponse();

            return response.toString();
        }
        catch (SocketTimeoutException x) {
            Log.e(TAG + ": ", "TIMEOUT");
            LogManagerClass.writeLog(TAG + ": " + "TIMEOUT");

            return "-10";
        }
        catch (SoapFault e) {
            StackTraceElement[] stack = e.getStackTrace();
            String Trace = " ";
            for (StackTraceElement line : stack) {
                Trace += line.toString();
            }
            Log.e(TAG + ": ", Trace);
            LogManagerClass.writeLog(TAG + ": " + Trace);

            return "-10";
        }
        catch (IOException x) {
            Log.e(TAG + ": ", x.getMessage());
            LogManagerClass.writeLog(TAG + ": " + x.getMessage());

            return "-10";
        }
        catch (XmlPullParserException x) {
            Log.e(TAG + ": ", x.getMessage());
            LogManagerClass.writeLog(TAG + ": " + x.getMessage());

            return x.getMessage();
        }
    }

    public Post[] getMyPictures(int fromPosition, int userID, int myID, Context context) {

        String request = SoapUtil.MODE_MINE + "@" + fromPosition
                    + "@" + userID + "@" + myID + "@"
                    + SoapUtil.ALBUM_ID;
        //
        return downloadPicturesInfo(request);
    }

    public Post[] getNewsPictures(int fromPosition, int userID, int myID, Context context) {

        String request = SoapUtil.MODE_NEWS + "@" + fromPosition
                    + "@" + userID + "@" + myID + "@"
                    + SoapUtil.ALBUM_ID;
        //
        return downloadPicturesInfo(request);
    }

    public Post[] getTagsPictures(int fromPosition, int userID, int myID, String tag, Context context) {

        String request = SoapUtil.MODE_TAGS + "@" + fromPosition
                    + "@" + userID + "@" + myID + "@"
                    + SoapUtil.ALBUM_ID + "@" + tag;
        //
        return downloadPicturesInfo(request);
    }

    public String uploadPicture(String[] data, String tags, int upload, byte[] picture) {

        String info = "";
        //
        if (upload == UPLOAD_PICTURE) {
            METHOD_NAME = "uploadPicture";
            SOAP_ACTION = "http://ShareUp.com/uploadPicture";
            // ADDING THE TAGS TO THE UPLOADED IMAGE
        }
        else
            if (upload == UPLOAD_PROFILE) {
                METHOD_NAME = "setAsProfilePicture";
                SOAP_ACTION = "http://ShareUp.com/setAsProfilePicture";
            }
            else
                if (upload == UPLOAD_COVER) {
                    METHOD_NAME = "setAsCoverPicture";
                    SOAP_ACTION = "http://ShareUp.com/setAsCoverPicture";
                }
        //
        Request = new SoapObject(SoapUtil.NAMESPACE, METHOD_NAME);
        //
        if (upload == UPLOAD_PICTURE) {
            if (tags == null || tags.isEmpty()) {
                tags = "";
            }
            Request.addProperty("tags", tags);
        }
        for (int i = 0; i < data.length; i++) {
            info += data[i] + "#";

        }
        Object response = null;
        try {

            Request.addProperty("data", info);
            Request.addProperty("picBytes", picture);
            //
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            new MarshalBase64().register(envelope);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(Request);
            HttpTransportSE httpTransport = new HttpTransportSE(SoapUtil.URL, SoapUtil.TIMEOUT);
            httpTransport.call(SOAP_ACTION, envelope);

            response = envelope.getResponse();

            Log.e(TAG + ": ", response.toString());

            return response.toString();
        }
        catch (SocketTimeoutException x) {
            Log.e(TAG + ": ", "TIMEOUT");
            LogManagerClass.writeLog(TAG + ": " + "TIMEOUT");

            return "-10";
        }
        catch (SoapFault e) {
            StackTraceElement[] stack = e.getStackTrace();
            String Trace = " ";
            for (StackTraceElement line : stack) {
                Trace += line.toString();
            }
            Log.e(TAG + ": ", Trace);
            LogManagerClass.writeLog(TAG + ": " + Trace);

            return e.getMessage();
        }
        catch (IOException x) {
            Log.e(TAG + ": ", x.getMessage());
            LogManagerClass.writeLog(TAG + ": " + x.getMessage());

            return "-10";
        }
        catch (XmlPullParserException x) {
            Log.e(TAG + ": ", x.getMessage());
            LogManagerClass.writeLog(TAG + ": " + x.getMessage());

            return x.getMessage();
        }

    }

    private Post[] downloadPicturesInfo(String requestedPictures) {

        METHOD_NAME = "getAllPictures";
        SOAP_ACTION = "http://ShareUp.com/getAllPictures";
        // /////////////////////////////////////////////////////////////////////////
        Request = new SoapObject(SoapUtil.NAMESPACE, METHOD_NAME);
        Request.addProperty("data", requestedPictures);
        // //////////////////////////////////////////////////////////////////////////
        envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(Request);
        HttpTransportSE trans = new HttpTransportSE(SoapUtil.URL, SoapUtil.TIMEOUT);
        // //////////////////////////////////////////////////////////////////////////
        Object response = null;
        //
        try {
            trans.call(SOAP_ACTION, envelope);
            response = envelope.getResponse();

        }
        catch (SocketTimeoutException x) {
            Log.e(TAG + ": ", "TIMEOUT");
            LogManagerClass.writeLog(TAG + ": " + "TIMEOUT");
            Post[] p = new Post[1];
            Post res = new Post();
            res.setID(-10);
            p[0] = res;
            return p;
        }
        catch (SoapFault e) {
            StackTraceElement[] stack = e.getStackTrace();
            String Trace = " ";
            for (StackTraceElement line : stack) {
                Trace += line.toString();
            }
            Log.e(TAG + ": ", Trace);
            LogManagerClass.writeLog(TAG + ": " + Trace);
        }
        catch (IOException x) {
            Log.e(TAG + ": ", "FILEIO");
            LogManagerClass.writeLog(TAG + ": " + "FILEIO");

            Post[] p = new Post[1];
            Post res = new Post();
            res.setID(-10);
            p[0] = res;
            return p;
        }
        catch (XmlPullParserException x) {
            Log.e(TAG + ": ", x.getMessage());
            LogManagerClass.writeLog(TAG + ": " + x.getMessage());
        }

        return getAllPictures(response);
    }

    private Post[] getAllPictures(Object soap) {

        String RES = soap.toString();
        try {
            JSONArray jsonArray = new JSONArray(RES);
            Post[] pics = new Post[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jo = new JSONObject(jsonArray.getString(i));

                // PICTURE INFO
                int ID = Integer.parseInt(jo.getString("ID"));
               
                String Comment = "";
                try {
                    Comment = URLDecoder.decode(jo.getString("Comment"), "UTF-8");
                }
                catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String PathThumb = jo.getString("PathThumb");
                String PathFull = jo.getString("PathFull");
                String PublicationDate = jo.getString("PublicationDate");
                String UploadedFrom = jo.getString("UploadedFrom");
                String Tags = jo.getString("Tags");
                Integer Permission = jo.getInt("Permission");
                Integer.parseInt(jo.getString("Private"));
                int Width = Integer.parseInt(jo.getString("Width"));
                int Height = Integer.parseInt(jo.getString("Height"));
                int Length = Integer.parseInt(jo.getString("Length"));
                // USER INFO
                String Owner = jsonArray.getJSONObject(i).getJSONObject("User").toString();
                jo = new JSONObject(Owner);
                int OwnerId = Integer.parseInt(jo.getString("ID"));
                String OwnerName = jo.getString("RealName");
                String OwnerProfile = jo.getString("ProfilePicture");
                String CoverPicture = jo.getString("CoverPicture");
                // PICTURE COUNTERS
                PictureInfo lk = new PictureInfo();
                String PictureCounters = jsonArray.getJSONObject(i).getJSONObject("PictureCounters").toString();
                jo = new JSONObject(PictureCounters);
                int CommentsCounter = Integer.parseInt(jo.getString("CommentsCount"));
                int LikesCount = Integer.parseInt(jo.getString("LikesCount"));
                int isMine = Integer.parseInt(jo.getString("isMine"));
                lk.setIsMine(isMine);
                lk.setCommentsCount(CommentsCounter);
                lk.setLikesCount(LikesCount);
                // GEOTAGS
                GeoTag gtag = new GeoTag();
                String GeoTags = jsonArray.getJSONObject(i).getJSONObject("GeoTag").toString();
                jo = new JSONObject(GeoTags);
                Double lat = Double.parseDouble(jo.getString("Latitude"));
                Double lon = Double.parseDouble(jo.getString("Longitude"));
                String Address = jo.getString("Address");
                String City = jo.getString("City");
                String Country = jo.getString("Country");
                String Album = jsonArray.getJSONObject(i).getJSONObject("Album").toString();
                jo = new JSONObject(Album);
                int Albumid = jo.getInt("ID");
                Albums al = new Albums();
                al.setID(Albumid);
              
                //
                gtag.setAddress(Address);
                gtag.setCity(City);
                gtag.setCountry(Country);
                gtag.setIDPicture(ID);
                gtag.setLatitude(lat);
                gtag.setLongitude(lon);
                // PASSING
                Post adp = new Post();
                User user = new User();
                user.setID(OwnerId);
                user.setCoverPicture(CoverPicture);
                user.setProfilePicture(OwnerProfile);
                user.setRealName(OwnerName);
                adp.setComment(Comment);
                adp.setPathFull(PathFull);
                adp.setPathThumb(PathThumb);
                adp.setHeight(Height);
                adp.setWidth(Width);
                adp.setLength(Length);
                adp.setID(ID);
                adp.setUser(user);
                adp.setUploadedFrom(UploadedFrom);
                adp.setPublicationDate(PublicationDate);
                adp.setTags(Tags);
                adp.setPictureCounters(lk);
                adp.setGeoTag(gtag);
                adp.setPermission(Permission);
                adp.setAlbum(al);

                pics[i] = adp;
            }
            return pics;

        }
        catch (JSONException x) {
            Log.e(TAG + ": ", x.getMessage());
            LogManagerClass.writeLog(TAG + ": " + x.getMessage());
            return null;
        }

    }
}
